import React,{useState,useEffect} from 'react'
import {getAdminList,deleteAdmin,addAdmin,updateAdmin} from '@/api/admin'
import {Button, Table,Space,Tag, Popconfirm,Drawer, Select,Input,Tree, message,Modal} from 'antd'
import usePagination from '@/hooks/usePagination'
import {
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons';
import {useSize} from 'ahooks'
import { useMemo } from 'react';
import menus from '@/router/menus'
import { useSelector,useDispatch } from 'react-redux';
import {changeRole,changeCheckedKeys} from '@/store/modules/admin'
import store from 'store2'
export default function AdminList() {
  const [adminList,setAdminList] = useState([])
  const [height] = useState(document.body.offsetHeight)
  const size = useSize(document.querySelector('body')); // 使用useSize这个ahooks监听body的尺寸变化
  const dispatch = useDispatch()
  
  // 定义列
  const columns = [
    {
      title:'序号',
      render:(text, record, index)=>{
        return <span>{ config.pageSize*(config.current-1) + index + 1}</span>
      }
    },
    {
      title: '账户',            // 列的名字
      dataIndex: 'adminname',  // colums对象的dataIndex作用，就会将dataSource每个对象的对应的name取出来放在此列
    },
    {
      title:'角色',
      dataIndex:'role',
      render:(text,record,index)=>{
        return text ===2 ? <Tag color="cyan">超级管理员</Tag> : <Tag>普通管理员</Tag>
      }
    },
    {
      title:'操作',
      render:(text, record, index)=>{
        return <Space>
          <Button type="primary" shape="circle" icon={<EditOutlined />} onClick={()=>{
            // 需要打开Modal
            setIsModalOpen(true)
            // 点击编辑按钮的时候，需要将当前record数据进行表单回填操作
            setAdminname(record.adminname)
            setRole(record.role)
            setCheckedKeys(record.checkedKeys)
          }}/>
          <Popconfirm
            title="想要删除吗?"
            description="Are you sure to delete!"
            onConfirm={()=>{
              deleteAdmin({adminid:record.adminid}).then(()=>{
                getAdminListData() // 删除成功后，需要重新调用后台获取管理员列表信息接口
              })
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button danger type="primary" shape="circle" icon={<DeleteOutlined />}/>
          </Popconfirm>
          
        </Space>
      }
    }
  ];
  
  
  const getAdminListData = ()=>{
    getAdminList().then(res=>{
      setAdminList(res.data.data)
    })
  }

  // 进行了异步请求，获取后端返回的管理员信息列表
  useEffect(()=>{
    getAdminListData()
  },[])

  // 调用hooks函数
  const config = usePagination({
    size:5,
    showQuickJumper:false
  })

  // 实现多选删除
  const [selectionType] = useState('checkbox');
  const [selectedRowKeys,setSelectedRowKeys] = useState([])
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedRowKeys(selectedRows)
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      name: record.name,
    }),
  };
  const flag = useMemo(()=>{
    return selectedRowKeys.length>0
  },[selectedRowKeys.length])

  // 设置打开右侧的Drawer抽屉面板
  const [open,setOpen] = useState(false)

  //treeData = [ {title:,key:,children:[{title,key,children}]} ]
  const getTreeData = menus => {
    const arr = []
    menus.forEach(item=>{
      let obj = {}
      if(item.children){
        obj = {title:item.label,key:item.keyid,children:getTreeData(item.children)}
      }else{
        obj = {title:item.label,key:item.keyid}
      }
      arr.push(obj)
    })
    return arr
  }
  const treeData = getTreeData(menus)
  // 设置选中的checkedKeys
  const [checkedKeys,setCheckedKeys] = useState(['0-0'])
  const [adminname,setAdminname] = useState('')
  const [password,setPassword] = useState('')
  const [role,setRole] = useState(1)
  const clearDrawer = ()=>{
    setAdminname('')
    setPassword('')
    setRole(1)
    setCheckedKeys(['0-0'])
    setOpen(false)
  }
  // 实现管理员的添加方法
  const onAdd = ()=>{
    const result = {adminname,password,role,checkedKeys}  // 前后端联调  
    addAdmin(result).then((res)=>{
      if(res.data.code === '10004'){
        message.error(res.data.message)
      }else{
        // 添加成功后，需要清空，否则导致再点击添加的时候出现上次的结果
        clearDrawer()
        getAdminListData() // 添加管理员成功后，重新请求列表
      }
    })
  }

  // 定义编辑管理员的业务
  const [isModalOpen,setIsModalOpen] = useState(false)
  let name = useSelector(state=>state.admin.adminname)
  let userRole = useSelector(state=>state.admin.role)
  const onUpdate = ()=>{
    let result = {adminname,password,role,checkedKeys}
    updateAdmin(result).then(()=>{
      clearDrawer() // 重置状态，否则添加管理员的时候会有之前的记录
      setIsModalOpen(false)
      getAdminListData() 

      // 需要判断如果更改的是当前登录进去的用户的话
      if(name === adminname){
        dispatch(changeRole(role)) // 将rtk里面的role进行更改
        dispatch(changeCheckedKeys(checkedKeys)) // 将rtk里面的checkedKeys进行更改
        store.add('users',{role,checkedKeys}) // 只是更新role/checkedKeys
      }
    })
  }
  return (
    <Space style={{width:'100%'}} direction='vertical'>
      <Space>
        <Button type='primary' onClick={()=>setOpen(true)}>添加管理员</Button>
        {
          flag && <Button type='primary' onClick={()=>{

            if(userRole < 2){
              message.error('暂无权限批量删除！')
              return 
            }
            // 接口没有提供批量删除的，只提供了单条删除接口
            // 每个删除都是基于Promise的，采用Promise.all方法
            const arr = []
            selectedRowKeys.forEach(item=>{
              arr.push(deleteAdmin({adminid:item.adminid}))
            })
            Promise.all(arr).then(()=>{
              getAdminListData()
            })
          }}>批量删除</Button>
        }
      </Space>
      <Table 
        dataSource={adminList} 
        columns={columns} 
        rowKey={record=>record.adminid}
        scroll={{
          y: (size ? size.height : height)-350
        }}
        pagination={config}
        rowSelection={{
          type: selectionType,
          ...rowSelection,
        }}
      />
       <Drawer title="添加管理员" placement="right" onClose={()=>{clearDrawer()}} open={open}>
        <Space direction='vertical' style={{display:'flex'}}>
          <Input placement='账户名' value={adminname} onChange={e=>setAdminname(e.target.value)}/>
          <Input placement='密码'  value={password} onChange={e=>setPassword(e.target.value)}/>
          <Select defaultValue={1} style={{width:'100%'}} value={role} onChange={value=>setRole(value)}>
            <Select.Option value={1}>管理员</Select.Option>
            <Select.Option value={2}>超级管理员</Select.Option>
          </Select>
          选择管理员的权限:
          <Tree
            checkable
            treeData={treeData}
            checkedKeys={checkedKeys}
            onCheck={(checkedKeys)=>{
              setCheckedKeys(checkedKeys)
            }}
          />
          <Button type='primary' onClick={onAdd}>添加管理员</Button>
        </Space>
      </Drawer>
      {/*进行管理员信息编辑的Modal*/}
      <Modal footer={null} title="修改管理员" open={isModalOpen}  onCancel={()=>{
        clearDrawer()
        setIsModalOpen(false)
      }}>
        <Space direction='vertical' style={{display:'flex'}}>
          <Input disabled placement='账户名' value={adminname} onChange={e=>setAdminname(e.target.value)}/>
          <Select defaultValue={1} style={{width:'100%'}} value={role} onChange={value=>setRole(value)}>
            <Select.Option value={1}>管理员</Select.Option>
            <Select.Option value={2}>超级管理员</Select.Option>
          </Select>
          选择管理员的权限:
          <Tree
            checkable
            treeData={treeData}
            checkedKeys={checkedKeys}
            onCheck={(checkedKeys)=>{
              setCheckedKeys(checkedKeys)
            }}
            defaultExpandAll
          />
          <Button type='primary' onClick={onUpdate}>修改管理员</Button>
        </Space>
      </Modal>
    </Space>
  )
}
